package com.edu.demo.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;

@Configuration
public class RedisConfig {
    //序列化器 redisTemplate
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String,Object> redisTemplate=new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);

        //设置key的序列化器
        redisTemplate.setKeySerializer(new StringRedisSerializer());

        //设置key的序列化器
        JavaTimeModule javaTimeModule = new JavaTimeModule();

        //设置value的序列化器
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());

        //设置序列化时间格式
        ObjectMapper objectMapper = new ObjectMapper();
        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.of("Asia/shanghai"))));
        objectMapper.registerModule(javaTimeModule);

        //设置value的序列化器，使用自定义的ObjectMapper
        Jackson2JsonRedisSerializer<Object> j2rs = new Jackson2JsonRedisSerializer<>(Object.class);
        j2rs.setObjectMapper(objectMapper);
        redisTemplate.setHashValueSerializer(j2rs);

        //设置hash key和value的序列化器
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(j2rs);

        return redisTemplate;
    }
}
